package cn.iocoder.yudao.module.infra.okhttp;

import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;

import java.util.concurrent.TimeUnit;

public class OkHttpUtils {
    private static final Dispatcher dispatcher;

    static {
        dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(500);         // 总并发数设置为QPS水平
        dispatcher.setMaxRequestsPerHost(300);   // 单个后端服务最大并发，适度放宽
    }

    private static final OkHttpClient defaultClient = new OkHttpClient.Builder()
            .connectionPool(new ConnectionPool(
                    300, 5, TimeUnit.MINUTES
            ))
            .dispatcher(dispatcher)
            // 连接服务器的超时时间
            .connectTimeout(10, TimeUnit.SECONDS)
            // 服务器返回数据的读取超时时间
            .readTimeout(30, TimeUnit.SECONDS)
            // 向服务器写数据的超时时间
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();

    private static final OkHttpClient llmClient = defaultClient.newBuilder()
            .connectTimeout(300, TimeUnit.SECONDS)
            .writeTimeout(300, TimeUnit.SECONDS)
            .readTimeout(300, TimeUnit.SECONDS)
            .build();

    private static final OkHttpClient ttsClient = defaultClient.newBuilder()
            .connectTimeout(3, TimeUnit.SECONDS)
            .writeTimeout(6, TimeUnit.SECONDS)
            .readTimeout(6, TimeUnit.SECONDS)
            .build();

    private static final OkHttpClient embeddingClient = defaultClient.newBuilder()
            .connectTimeout(3, TimeUnit.SECONDS)
            .writeTimeout(6, TimeUnit.SECONDS)
            .readTimeout(6, TimeUnit.SECONDS)
            .build();

    public static OkHttpClient getDefaultHttpClient() {
        return defaultClient;
    }

    public static OkHttpClient getLlmClient() {
        return llmClient;
    }

    public static OkHttpClient getTtsClient() {
        return ttsClient;
    }

    public static OkHttpClient getEmbeddingClient() {
        return embeddingClient;
    }

}
